//
//  AddressViewController.m
//  GoBigMarket
//
//  Created by 王天义 on 16/8/17.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "CartAddressViewController.h"
#import "NewAddressViewController.h"
#import "AddressTableViewCell.h"
#import "AddressModel.h"
#import "NewAddressModel.h"
#import "ConfirmOderViewController.h"
@interface CartAddressViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,weak)UITableView *addressView;
@end

@implementation CartAddressViewController

#pragma mark --- 懒加载

- (NSMutableArray *)datas{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.addressView.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"选择收货地址";
    // 马上进入刷新状态
    [self getAddressData];
    [self creatTableView];
    
//    self.addressView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getAddressData)];
//    [self.addressView.mj_header beginRefreshing];
}

#pragma mark --- 加载视图

- (void)creatTableView{

    UITableView *addressView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, XNWindowWidth, XNWindowHeight - 64 - 49) style:UITableViewStylePlain];
    addressView.delegate = self;
    addressView.dataSource = self;
    addressView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.addressView = addressView;
    [self.view addSubview:self.addressView];
    
    
    UIButton *newAddressBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, XNWindowHeight - 64 - 50, XNWindowWidth, 50)];
    [newAddressBtn addTarget:self action:@selector(newAddressBtnClick) forControlEvents:UIControlEventTouchUpInside];
    newAddressBtn.backgroundColor = [UIColor colorWithRed:1/255.0 green:196/255.0 blue:92/255.0 alpha:0.7];
    [newAddressBtn setTitle:@"+   新增地址" forState:UIControlStateNormal];
    [self.view addSubview:newAddressBtn];

}

#pragma mark --- tableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"addressViewCellID";
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:NSStringFromClass([AddressTableViewCell class]) bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellID];
        nibsRegistered = YES;
    }
    AddressTableViewCell *addressViewCell = (AddressTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellID];
    [addressViewCell setSelectionStyle:UITableViewCellSelectionStyleNone];

    
    if (self.datas == nil) {
        
    }else{
        AddressModel *model = self.datas[indexPath.row];
        addressViewCell.nameLabel.text = model.ShipTo;
        addressViewCell.phoneLabel.text = model.Phone;
        addressViewCell.addressLabel.text = model.Address;
        
        addressViewCell.bianjiBtn.tag = indexPath.row;
        [addressViewCell.bianjiBtn addTarget:self action:@selector(bianjiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        addressViewCell.shanchuBtn.tag = indexPath.row;
        [addressViewCell.shanchuBtn addTarget:self action:@selector(shanchuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return addressViewCell;
}

- (void)newAddressBtnClick{
    NewAddressViewController *newAddressVC = [[NewAddressViewController alloc]init];
    [self.navigationController pushViewController:newAddressVC animated:NO];
}


#pragma mark --- tableView数据源代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return XNWindowHeight / 7;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    AddressModel *model = self.datas[indexPath.row];
#pragma mark --- 获取到数据存到本地

    //地址Id,收货人电话,收货人,收货人地址
    
    [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInteger:model.Id] forKey:@"ShipToAddressId"];
    [[NSUserDefaults standardUserDefaults]setObject:model.Phone forKey:@"ShipToPhone"];
    [[NSUserDefaults standardUserDefaults]setObject:model.ShipTo forKey:@"ShipTo"];
    [[NSUserDefaults standardUserDefaults]setObject:model.Address forKey:@"ShipToAddress"];
    
    
    //创建一个消息对象
    NSNotification * notice = [NSNotification notificationWithName:@"addressChanged" object:nil userInfo:model.mj_keyValues];
    //发送消息
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)bianjiBtnClick:(id)sender{

    UIButton *btn = sender;
    NewAddressViewController *vc= [[NewAddressViewController alloc]init];
    [self.navigationController pushViewController:vc animated:NO];
    vc.isBianJi = YES;
    NewAddressModel *model = self.datas[btn.tag];
    [vc.datas addObject:model];
}

#pragma mark --- 删除地址请求

- (void)shanchuBtnClick:(id)sender{
    
    UIButton *btn = sender;
    AddressModel *model = self.datas[btn.tag];
    NSDictionary *dicStr = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"Id":[NSNumber numberWithInteger:model.Id]};
    
    [CQNetWorkTools GETWithURL:DeleteShippingAddress par:dicStr success:^(id responseObject) {
        DLog(@"success%@",responseObject);
        if ([[responseObject objectForKey:@"Err"] intValue]) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }else{
            // 马上进入刷新状态
//            [self.addressView.mj_header beginRefreshing];
            // 刷新表格
            [self.addressView reloadData];
            
            // 拿到当前的下拉刷新控件，结束刷新状态
//            [self.addressView.mj_header endRefreshing];
            }
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
    }];
}



#pragma mark --- 获取地址请求

- (void)getAddressData{
    
    NSDictionary *par = @{@"ShouJiHao":GETPHONE,
                          @"Token":GETTOKEN,
                          @"Duuid":GETUUID};
    
    [CQNetWorkTools GETWithURL:GetShippingAddress par:par success:^(id responseObject) {
        if ([[responseObject objectForKey:@"Err"] intValue]) {
            [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
            [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        }else{
            
            NSArray *dataArr = [responseObject objectForKey:@"UserShippingAddress"];
            [self.datas removeAllObjects];
            for (NSDictionary *dict in dataArr) {
                AddressModel *model = [AddressModel mj_objectWithKeyValues:dict];
                [self.datas addObject:model];
            }
            // 刷新表格
            [self.addressView reloadData];
        }
          [self.addressView.mj_header endRefreshing];
    } filed:^(NSError *error) {
        DLog(@"失败===%@", error);
        [SVProgressHUD  showWithStatus:@"请检查网络"];
        [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
        [self.addressView.mj_header endRefreshing];
    }];
}

- (void)dismiss{
    [SVProgressHUD dismiss];
}

@end
